#!/usr/bin/python
import sys
import XenAPI
import urllib2
import base64
from xml.dom.minidom import parse, parseString

path 	  =  "./"
resultxml = path +"result.xml"
tpmcert     = path + "tpm.cert"
aiktcpa     = path + "aik_tcpa.pub"
ekpub      = path +  "ek_pem.pub"
aikpub      = path + "aik_pem.pub"

def read_xml(result):
    try:
        dom = parseString(result)
        root = dom.getElementsByTagName("xentxt:xentxtdata")
        tpmcert_node = dom.getElementsByTagName('xentxt:TPM_Endorsement_Certficate')[0]
        ekpub_node  = dom.getElementsByTagName("xentxt:TPM_Endorsement_KEY_PEM")[0]
        aiktcpa_node  = dom.getElementsByTagName("xentxt:TPM_Attestation_KEY_TCPA")[0]
        aikpub_node  = dom.getElementsByTagName("xentxt:TPM_Attestation_KEY_PEM")[0]
    except:
        print "Error parsing the Result XML from XenServer"
        print result
    try:
        f= open (tpmcert,"w")
        cert = base64.b64decode(tpmcert_node.firstChild.nodeValue)
        f.write(cert)
        f.close()
    except:
        pass
    f = open(ekpub,"w")
    key = base64.b64decode(ekpub_node.firstChild.nodeValue)
    f.write(key)
    f.close()

    f = open(aiktcpa,"w")
    f.write(base64.b64decode(aiktcpa_node.firstChild.nodeValue))
    f.close()

    f = open(aikpub,"w")
    f.write( base64.b64decode(aikpub_node.firstChild.nodeValue))
    f.close()



def main(session):
    args = {}
    hostlist = session.xenapi.host.get_all()
    hid = 1
    if (len(hostlist) > 1):
        print "\t ## Pool host label names ## \n"
        for x in hostlist:
            print "\t "+ session.xenapi.host.get_name_label(x)
        hid = int(raw_input('\n which host?? (enter no from 1)   ::'))
        if ( (hid < 1)  and (hid > (len(hostlist))) ) :
            print "range is 1 to %d" %len(hostlist)
            sys.exit(1)
    host_ref = hostlist[hid-1]

    #host_ref = session.xenapi.session.get_this_host(session.handle)
    try:
        ret_val = session.xenapi.host.call_plugin(host_ref, 'tpmGetAttestationKey', 'main', args)
    except:
        print '## Exception in calling TPM Plugins on Xenserver ##'
        print '## XEN TPM plugins may not be installed ##'
        raise
    print ret_val
    read_xml(ret_val)

if __name__ == "__main__":
    if len(sys.argv) <> 4:
		print "Usage:"
		print sys.argv[0], "<XenServer host> <username> <password> "
		sys.exit(1)
    url = "https://" + sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]
    try:
        session = XenAPI.Session(url)
        session.xenapi.login_with_password(username, password)
    except:
        print 'Xapi unable to Connect to Xenserver'
    try:
        main(session)
    except Exception, e:
        print str(e)
        raise

